from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import json
from datetime import datetime

from database import get_db, DataSource, DataRecord
from services.cache_service import CacheService, CacheKeys

router = APIRouter()

class DataSourceCreate(BaseModel):
    name: str
    url: str
    api_key: Optional[str] = None
    data_type: str
    update_interval: int = 3600

class DataSourceUpdate(BaseModel):
    name: Optional[str] = None
    url: Optional[str] = None
    api_key: Optional[str] = None
    data_type: Optional[str] = None
    update_interval: Optional[int] = None
    is_active: Optional[bool] = None

@router.get("/")
async def get_data_sources(db: Session = Depends(get_db)):
    """获取所有数据源"""
    try:
        sources = db.query(DataSource).all()
        
        result = []
        for source in sources:
            result.append({
                "id": source.id,
                "name": source.name,
                "url": source.url,
                "data_type": source.data_type,
                "update_interval": source.update_interval,
                "is_active": source.is_active,
                "created_at": source.created_at.isoformat(),
                "updated_at": source.updated_at.isoformat()
            })
        
        return {
            "success": True,
            "data_sources": result,
            "total": len(result)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取数据源失败: {str(e)}")

@router.post("/")
async def create_data_source(
    data_source: DataSourceCreate,
    db: Session = Depends(get_db)
):
    """创建数据源"""
    try:
        # 检查名称是否已存在
        existing = db.query(DataSource).filter(DataSource.name == data_source.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="数据源名称已存在")
        
        # 创建新数据源
        new_source = DataSource(
            name=data_source.name,
            url=data_source.url,
            api_key=data_source.api_key,
            data_type=data_source.data_type,
            update_interval=data_source.update_interval
        )
        
        db.add(new_source)
        db.commit()
        db.refresh(new_source)
        
        return {
            "success": True,
            "data_source": {
                "id": new_source.id,
                "name": new_source.name,
                "url": new_source.url,
                "data_type": new_source.data_type,
                "update_interval": new_source.update_interval,
                "is_active": new_source.is_active,
                "created_at": new_source.created_at.isoformat()
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建数据源失败: {str(e)}")

@router.put("/{source_id}")
async def update_data_source(
    source_id: int,
    data_source: DataSourceUpdate,
    db: Session = Depends(get_db)
):
    """更新数据源"""
    try:
        source = db.query(DataSource).filter(DataSource.id == source_id).first()
        if not source:
            raise HTTPException(status_code=404, detail="数据源不存在")
        
        # 更新字段
        update_data = data_source.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(source, field, value)
        
        source.updated_at = datetime.utcnow()
        db.commit()
        db.refresh(source)
        
        # 清除相关缓存
        cache_key = CacheKeys.data_source_key(source_id)
        await CacheService.delete(cache_key)
        
        return {
            "success": True,
            "data_source": {
                "id": source.id,
                "name": source.name,
                "url": source.url,
                "data_type": source.data_type,
                "update_interval": source.update_interval,
                "is_active": source.is_active,
                "updated_at": source.updated_at.isoformat()
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新数据源失败: {str(e)}")

@router.delete("/{source_id}")
async def delete_data_source(source_id: int, db: Session = Depends(get_db)):
    """删除数据源"""
    try:
        source = db.query(DataSource).filter(DataSource.id == source_id).first()
        if not source:
            raise HTTPException(status_code=404, detail="数据源不存在")
        
        # 删除相关数据记录
        db.query(DataRecord).filter(DataRecord.source_id == source_id).delete()
        
        # 删除数据源
        db.delete(source)
        db.commit()
        
        # 清除缓存
        cache_key = CacheKeys.data_source_key(source_id)
        await CacheService.delete(cache_key)
        
        return {
            "success": True,
            "message": f"数据源 '{source.name}' 已删除"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除数据源失败: {str(e)}")

@router.get("/{source_id}/data")
async def get_source_data(
    source_id: int,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """获取数据源的数据记录"""
    try:
        source = db.query(DataSource).filter(DataSource.id == source_id).first()
        if not source:
            raise HTTPException(status_code=404, detail="数据源不存在")
        
        # 获取最新的数据记录
        records = db.query(DataRecord).filter(
            DataRecord.source_id == source_id
        ).order_by(DataRecord.timestamp.desc()).limit(limit).all()
        
        data = []
        for record in records:
            try:
                record_data = json.loads(record.data_json)
                data.append({
                    "id": record.id,
                    "timestamp": record.timestamp.isoformat(),
                    "data": record_data
                })
            except json.JSONDecodeError:
                continue
        
        return {
            "success": True,
            "source": {
                "id": source.id,
                "name": source.name,
                "data_type": source.data_type
            },
            "records": data,
            "total": len(data)
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取数据记录失败: {str(e)}")

@router.post("/{source_id}/data")
async def add_source_data(
    source_id: int,
    data: Dict[str, Any],
    db: Session = Depends(get_db)
):
    """添加数据源的数据记录"""
    try:
        source = db.query(DataSource).filter(DataSource.id == source_id).first()
        if not source:
            raise HTTPException(status_code=404, detail="数据源不存在")
        
        # 创建数据记录
        data_record = DataRecord(
            source_id=source_id,
            data_type=source.data_type,
            data_json=json.dumps(data, ensure_ascii=False)
        )
        
        db.add(data_record)
        db.commit()
        db.refresh(data_record)
        
        # 清除相关缓存
        cache_key = CacheKeys.dashboard_data_key(source.data_type)
        await CacheService.delete(cache_key)
        
        return {
            "success": True,
            "record": {
                "id": data_record.id,
                "timestamp": data_record.timestamp.isoformat(),
                "data_type": data_record.data_type
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加数据记录失败: {str(e)}")

@router.get("/types")
async def get_data_types():
    """获取支持的数据类型"""
    return {
        "success": True,
        "data_types": [
            {
                "type": "weather",
                "name": "天气数据",
                "description": "温度、湿度、风速等天气信息"
            },
            {
                "type": "covid",
                "name": "疫情数据",
                "description": "新冠感染人数、疫苗接种等疫情信息"
            },
            {
                "type": "flu",
                "name": "流感数据",
                "description": "流感监测数据、感染趋势等"
            },
            {
                "type": "traffic",
                "name": "交通数据",
                "description": "路况、拥堵指数等交通信息"
            },
            {
                "type": "air_quality",
                "name": "空气质量",
                "description": "PM2.5、AQI等空气质量指标"
            },
            {
                "type": "economic",
                "name": "经济数据",
                "description": "GDP、通胀率、就业率等经济指标"
            }
        ]
    }
